<template>
<div>
<div class="search">
  <input class="search-input" type="text" v-model="keyword" placeholder="输入城市名或拼音" />
</div>
<div class="search-content" v-show="keyword" ref='search'>
<div class="button-List">
  <div class="cityButton" @click="handleClick(item.name)" v-for="item of list" :key='item.id'>
    <div class="button">{{item.name}}</div>
  </div>
  </div>
  <ul>
    <li class="search-item" v-show="!list.length">
    没有找到匹配数据
  </li>
  </ul>
</div>
</div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleClick (city) {
      this.$store.dispatch('changeCity', city)
      this.$router.push('/')
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~style/varibles.styl'
.search
  background-color $bgColor
  color #fff
  padding 0 .2rem .1rem
  .search-input
    height .62rem
    width 100%
    line-height .62rem
    text-align center
    border-radius .06rem
    color #666
.search-content
  z-index 1
  overflow hidden
  position absolute
  top 1.58rem
  left  0
  right 0
  bottom 0
  background #fff
  .search-item
    line-height .2rem
    color #333
    font-size .3rem
    text-align center
  .button-List
    padding .2rem
    overflow hidden
    .cityButton
      float left
      width 33.33%
      .button
        padding .2rem
        margin .2rem
        border .02rem solid #ccc
        border-radius .06rem
        text-align center
</style>

